<?php

namespace app\shop\controller;

use app\Base;
use app\service\shop\LoginServices;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\response\Json;
use think\response\View;

/**
 * 商城登陆
 * User : Du
 * Date : 2022/11/27
 * Time : 15:32
 * Class Login
 * @package projects\controller\shop
 */
class Login extends Base
{

    /**
     * 验证规则
     * User : Du
     * Date : 2022/11/27
     * Time : 15:41
     * @var array|string[]
     */
    public array $LoginRule = [
        'mobile' => 'require|mobile',
        'password' => 'require|min:6',
    ];

    public array $registerRule = [
        'username' => 'require',
        'mobile' => 'require|mobile',
        'password' => 'require|min:6',
        'password1' => 'require|confirm:password'
    ];

    public array $message = [
        'username.require' => '用户昵称不能为空',
        'mobile.require' => '手机号不能为空',
        'mobile.mobile' => '手机号格式不正确',
        'password.require' => '密码不能为空',
        'password.length' => '密码长度不能少于6个字符',
        'password1.password1' => '两次密码输入不一致',
    ];

    /**
     * 登陆页面
     * User : Du
     * Date : 2022/11/27
     * Time : 15:33
     * @return View
     */
    public function login(): View
    {
        return view('login');
    }

    /**
     * 用户登陆
     * User : Du
     * Date : 2022/11/27
     * Time : 19:30
     * @param LoginServices $services
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function userLogin(LoginServices $services): Json
    {
        try {
            validate($this->LoginRule, $this->message)->check($this->params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->returnData('fail', $e->getMessage());
        }
        $res = $services::userLogin($this->params);
        if (is_string($res)) {
            return $this->returnData('fail', $res);
        }
        return $this->returnData();
    }

    /**
     * 用户注册
     * User : Du
     * Date : 2022/11/27
     * Time : 17:06
     * @param LoginServices $services
     * @return Json
     */
    public function userRegister(LoginServices $services): Json
    {
        try {
            validate($this->registerRule, $this->message)->check($this->params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->returnData('fail', $e->getMessage());
        }
        $res = $services::userRegister($this->params);
        if (is_string($res)) {
            return $this->returnData('fail', $res);
        }
        return $this->returnData();
    }

}